package com.hoongs.v1.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hoongs.v1.entity.User;
import com.hoongs.v1.service.UserService;
import com.hoongs.v1.utils.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Result login(String username, String password, String code) {
        return userService.login(username, password, code);
    }

    @GetMapping("/logout")
    public Result logout() {
        return userService.logout();
    }

    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result save(User user) {
        return userService.save(user);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result add(@Validated User user, BindingResult bindingResult) {
        String res = Result.resultMsg(bindingResult);
        return StringUtils.isNotBlank(res) ? Result.opError(res) : userService.add(user);
    }

    @PostMapping("/remove")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result remove(String id) {
        return userService.remove(id);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result update(User user) {
        return userService.update(user);
    }

    @GetMapping("/selectById")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result selectById(String id) {
        return userService.selectById(id);
    }

    @GetMapping("/selectList")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result selectList(String name) {
        return userService.selectList(name);
    }

    @GetMapping("/selectPageList")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result selectPageList(Integer page, Integer size) {
        return userService.selectPageList(page, size);
    }

}
